package main

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type TimePoint struct {
	StartTime int64 `bson:"startTime"`
	EndTime   int64 `bson:"endTime"`
}

// 一条日志，序列化到 mongodb 需要转bson
type LogRecord struct {
	JobName   string    `bson:"jobName"`   // 任务名称
	Command   string    `bson:"command"`   // 命令
	Err       string    `bson:"err"`       // 脚本错误
	Content   string    `bson:"content"`   // 脚本输出
	TimePoint TimePoint `bson:"timePoint"` // 时间
}

// where
type FindByJobName struct {
	JobName   string    `bson:"jobName"`   // 任务名称
}

func main() {
	var (
		client     *mongo.Client
		database   *mongo.Database
		collection *mongo.Collection
		err        error
		condition *FindByJobName
		skip int64
		limit int64
		cursor *mongo.Cursor
		record *LogRecord
	)
	if client, err = mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://127.0.0.1:27017")); err != nil {
		fmt.Println(err)
		return
	}

	// 选择db
	database = client.Database("cron")

	// 选择表，插入记录的时候才会真正创建表
	collection = database.Collection("log")

	// Find
	condition = &FindByJobName{"job10"}
	skip,limit = 0,2 // 开始位置0，查询条数2
	if cursor,err = collection.Find(context.TODO(),condition,&options.FindOptions{Skip:&skip,Limit:&limit});err != nil{
		fmt.Println(err)
		return
	}

	// 关闭游标
	defer cursor.Close(context.TODO())

	// 游标遍历结果
	for cursor.Next(context.TODO()) {
		record = &LogRecord{}
		if err = cursor.Decode(record);err!=nil{
			fmt.Println(err)
			return
		}

		fmt.Println(record)
	}



}
